package com.hry.store.controller;

import com.hry.store.service.VerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * 验证码
 */
@Controller
public class VerifyCodeController {
    @Autowired
    private VerifyCodeService verifyCodeService;

    /**
     * 生成验证码
     * @param response
     */
    @RequestMapping("user/login/verifyCode")
    @ResponseBody
    public void verifyCode(HttpServletResponse response) {
        try {
            BufferedImage image = verifyCodeService.createVerifyCode(response);
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "JPEG", out);
            out.flush();
            out.close();
        } catch(Exception e) {
            e.printStackTrace();

        }
    }

    /**
     * 校验验证码
     */
    @RequestMapping("check/verifyCode")
    @ResponseBody
    public String checkVerifyCode(@RequestParam("codeValue") Integer codeValue, HttpServletRequest request) throws Exception {
        Boolean result = verifyCodeService.checkVerifyEmail(codeValue, request);
        if (result) {
            return "1";
        }
        return "2";
    }


}
